`
https://leetcode.cn/problems/rotate-list/
`

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
var rotateRight = function (head, k) {
  if (!head || !head.next) return head
  if (k === 0) return head

  // 快慢指针求出链表长度
  let slow = head, fast = head, len = 1
  while (fast && fast.next) {
    slow = slow.next
    fast = fast.next.next
    len += 2
  }
  if (!fast) len--

  // 如果 k 链表长度的倍数，直接返回原链表
  if (k % len === 0) return head

  // 确保 k 小于 len
  k = k % len

  // 找到倒数第 k+1 个结点
  let left = head, right = head
  for (let i = 0; i < k; i++) {
    if (right) right = right.next
  }

  while (right.next) {
    left = left.next
    right = right.next
  }

  // 此时 left 为倒数第 k+1 个结点

  const res = left.next

  // 将倒数 k 个结点拼接到链表头部
  right.next = head
  left.next = null

  return res
};